package com.plusjun.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.plusjun.common.utils.HttpUtils;
import com.plusjun.common.utils.PageUtils;
import com.plusjun.common.utils.Query;
import com.plusjun.gulimall.member.dao.MemberDao;
import com.plusjun.gulimall.member.dao.MemberLevelDao;
import com.plusjun.gulimall.member.entity.MemberEntity;
import com.plusjun.gulimall.member.entity.MemberLevelEntity;
import com.plusjun.gulimall.member.exception.PhoneExistException;
import com.plusjun.gulimall.member.exception.UsernameExistExcetion;
import com.plusjun.gulimall.member.service.MemberService;
import com.plusjun.gulimall.member.vo.MemberLoginVO;
import com.plusjun.gulimall.member.vo.MemberRegistVO;
import com.plusjun.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVO vo) {
        MemberEntity memberEntity = new MemberEntity();

        // 1、设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());
        //检查用户名手机号是否唯一
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUsername());
        // 保存用户名，手机号
        memberEntity.setUsername(vo.getUsername());
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setNickname(vo.getUsername());
        // MD5盐值加密,
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);
        this.baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        int count = this.count(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUserNameUnique(String username) throws UsernameExistExcetion {
        int count = this.count(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVO vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        // 1、去数据库使用 username或mobile查询
        MemberEntity memberDB = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if (memberDB == null) {
            // 登录失败
            return null;
        } else {
            // 获取数据库密码
            String passwordDB = memberDB.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            return passwordEncoder.matches(password, passwordDB) ? memberDB : null;
        }
    }

    @Override
    public MemberEntity login(SocialUser vo) throws Exception {
        // 1、根据uid判断当前用户使用以前用社交平台登录过系统
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", vo.getUid()));
        if (!Objects.isNull(memberEntity)) {
            // 如果根据传入的uid查询到又数据，说明该用户已经注册过
            MemberEntity updateMember = new MemberEntity();
            updateMember.setId(memberEntity.getId());
            updateMember.setAccessToken(vo.getAccess_token());
            updateMember.setExpiresIn(vo.getExpires_in());
            // 更新数据中的user信息
            this.baseMapper.updateById(updateMember);
            // 返回查询到的memberEntity
            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in());
            return memberEntity;
        } else {
            // 用户没有注册过，这是第一次通过社交平台登录,
            // 先去通过access_token和uid拿到其信息
            MemberEntity register = new MemberEntity();
                Map<String, String> query = new HashMap<>();
                query.put("access_token", vo.getAccess_token());
                query.put("uid", vo.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com",
                        "/2/users/show.json", "get", new HashMap<>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    //*********如果需要其他信息可以继续取出来
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    register.setNickname(name);
                    register.setGender("m".equals(gender) ? 1 : 0);
                }
            register.setSocialUid(vo.getUid());
            register.setAccessToken(vo.getAccess_token());
            register.setExpiresIn(vo.getExpires_in());
            this.baseMapper.insert(register);
            return register;
        }
    }
}